package com.sfx.concurrent.demo.concurrent.collectionsTest.list;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: sfx
 * Date: 2023-11-09
 * Time: 10:38
 */
public class TestCopyOnWriteArrayList {

    public static class Task implements Runnable {
        List<String> list = null;

        public Task(List<String> list) {
            this.list = list;
        }

        @Override
        public void run() {
            Iterator<String> iterator = list.iterator();
            while(iterator.hasNext()) {
                String name = Thread.currentThread().getName();
                System.out.println(name);
                list.add(name);
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        List<String> list = List.of("a","b","c");
        List<String> synchronizedList = Collections.synchronizedList(list);
        CopyOnWriteArrayList<String> copyOnWriteArrayList = new CopyOnWriteArrayList<>(list);
        Task task = new Task(copyOnWriteArrayList);
        for(int i =0;i<10;++i) {
            new Thread(task,"线程-" + i).start();
        }
        Thread.sleep(1000);
    }
}
